package server

import (
	"context"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/chat"
	imsdk2 "longmen/server/internal/rpc/tencentim/imsdk"
	"longmen/server/pkg/db/redis/cache"
	"longmen/server/pkg/protobuf"

	"errors"
	"strconv"

	"github.com/spf13/cast"

	"longmen/server/pkg/common/api_models"
)

type TencentIM struct {
	protobuf.UnimplementedTencentImServiceServer
}

func (s *TencentIM) ImportAccount(ctx context.Context, req *protobuf.AccountReq) (*protobuf.AccountResp, error) {
	user, err := chat.GetUser(int(req.UserId))
	if err != nil {
		return nil, err
	}

	if err != nil {
		return nil, errors.New("user not exists")
	}

	ok := imsdk2.GetSdk().CreateAccount(imsdk2.CreateAccountRequest{
		UserID:  strconv.Itoa(user.Id),
		Nick:    user.NickName,
		FaceURL: user.Avatar,
	})
	if !ok {
		return nil, err
	}
	return &protobuf.AccountResp{
		UserId:   strconv.Itoa(user.Id),
		Nickname: user.NickName,
		Avatar:   user.Avatar,
	}, err
}

func (s *TencentIM) GetLiveConfig(r *api_models.LiveConfigReq) (*api_models.LiveConfigResp, error) {
	configPri := cache.GetConfigPri()
	resp := &api_models.LiveConfigResp{}
	resp.Config.SumbumistegurK = configPri.SumbumistegurK
	resp.Config.Populaarsuse = configPri.Populaarsuse
	resp.Config.GiftFactor = configPri.GiftFactor
	resp.Config.GiftTime = configPri.GiftTime

	anchorlive, err := cache.GetAnchorLive(r.Anchorid)
	if err != nil {
		return nil, err
	}
	if anchorlive != nil {
		resp.Liveid = anchorlive.Liveid
		//resp.Start = anchorlive.Start
		//resp.End = anchorlive.End
		resp.Matchid = anchorlive.Matchid
		resp.Status = uint8(anchorlive.Status)
		resp.Nickname = anchorlive.Nickname
		resp.Heat = anchorlive.Heat //基础执度
		return resp, nil
	}
	resp.Status = 1
	return resp, nil
}

//func SetClientLogin(req *pb.CallbackReq) (ret *pb.CallbackResp, errorRes error) {
//	global.Log.Infof("joined:%v", req)
//
//	ret = &pb.CallbackResp{
//		ActionStatus: imsdk.OKActionStatus,
//		ErrorInfo:    "",
//		ErrorCode:    imsdk.TIM_CODE_OK,
//	}
//	roomId, _ := strconv.Atoi(req.GroupId)
//	reqUserId, _ := cast.ToInt64E(req.Operator_Account)
//	ut := im.GetClientUser(int(reqUserId))
//	if ut.UserId > 0 {
//		ret.ActionStatus = "OK"
//		ret.ErrorCode = 0 // 表示允许继续处理加群请求
//		return ret, nil
//	}
//	userInfo, err := api.GetAPI().GetUserInfo(int(reqUserId), roomId)
//	if err != nil {
//		global.Log.Errorf("userInfo err %v", userInfo)
//		ret.ActionStatus = imsdk.FailActionStatus
//		ret.ErrorCode = imsdk.TIM_ERROR_ERROR_SQL
//		ret.ErrorInfo = "系统操作超时"
//		return nil, err
//	}
//	clientUser := im.ClientUser{
//		Platform:   1,
//		UserId:     int(reqUserId),
//		RoomId:     roomId,
//		Token:      "",
//		ClientName: userInfo.NickName,
//		Avatar:     userInfo.Avatar,
//		Level:      int(userInfo.Level),
//		Vip:        int(userInfo.Vip),
//		UUID:       "",
//		Props:      nil,
//		Anonymouse: false,
//		Role:       0,
//		Permit:     userInfo.Permit,
//	}
//	if len(req.Operator_Account) > 10 { //游客，雪花id
//		clientUser.ClientName = "匿名" + req.Operator_Account[len(req.Operator_Account)-9:len(req.Operator_Account)-1]
//	} else { //正常用户才去取权限和挂件
//		//fixme 暂时 先取消这个从里面取背包
//		//clientUser.Props = api.GetAPI().GetUserBackPack(clientUser.SenderUid)
//		clientUser.Role = api.GetAPI().GetUserRole(clientUser.UserId, clientUser.RoomId)
//	}
//
//	im.SetClientUser(&clientUser)
//	ret.ActionStatus = "OK"
//	ret.ErrorCode = 0 // 表示允许继续处理加群请求
//	return ret, nil
//}

func (s *TencentIM) CreteGroup(ctx context.Context, req *protobuf.CreateGroupReq) (*protobuf.CreateGroupResp, error) {
	var g imsdk2.GetGroupInfoReq
	g.GroupIdList = []string{cast.ToString(req.AnchorId)}

	if exist, _ := imsdk2.GetSdk().GetGroupInfo(g); exist {
		global.Log.Debugf("群組已存在 %s", req.AnchorId)
		return &protobuf.CreateGroupResp{
			AnchorId:  req.AnchorId,
			GroupName: req.GroupName,
		}, nil
	}

	groupId := strconv.Itoa(int(req.AnchorId))
	createReq := imsdk2.CreateGroupRequest{
		OwnerAccount: strconv.Itoa(int(req.UserId)),
		GroupID:      groupId,
		Name:         req.GroupName,
	}
	_ = imsdk2.GetSdk().CreateGroup(createReq)
	//var err error
	//err = nil
	/*if res != true { //开失败
		err = fmt.Errorf("创建聊天室失败，请重试")
	}*/
	return &protobuf.CreateGroupResp{
		AnchorId:  req.AnchorId,
		GroupName: req.GroupName,
	}, nil
}
